<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { addEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from '@/apis/park';
import router from '@/router';
import type { AddEnterpriseParams, industryList } from '@/types/park';
import { ElMessage, type FormInstance, type FormRules, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute()
// 根据接口文档定义字段，用于表单双向绑定
const addForm = ref<AddEnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: undefined, // 营业执照url
  businessLicenseId: undefined // 营业执照id
})
//添加企业表单校验
const addFormRules = ref<FormRules>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ]
})
//获取行业列表
const industryList = ref<industryList[]>([])
const getIndustryList = async () => {
  const res = await getIndustryListAPI()
  industryList.value = res.data
}
getIndustryList()
//表单
const addFormRef = ref<FormInstance>()
//默认上传文件列表
const fileList = ref<UploadUserFile[]>([])
//自定义上传文件请求
const upload = async (options: UploadRequestOptions) => {
  console.log(options.file);
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'businessLicense')
  const res = await uploadAPI(fd)
  addForm.value.businessLicenseId = res.data.id
  addForm.value.businessLicenseUrl = res.data.url
  addFormRef.value?.validateField('businessLicenseUrl')
  return res.data.url
}
//移除文件时的操作
const removeFile = () => {
  addForm.value.businessLicenseId = undefined
  addForm.value.businessLicenseUrl = undefined
  addFormRef.value?.validateField('businessLicenseUrl')
}
//提交表单、添加企业
const submit = async () => {
  await addFormRef.value?.validate()
  try {
    await addEnterpriseAPI(addForm.value)
    router.back()
    ElMessage.success('添加成功！')
  } catch (err: any) {
    ElMessage.error(err.response.data.msg)
  }
}
//如果是编辑页面就给表单加数据
onMounted(async() => {
if(route.params.id)
{
  const res= await getEnterpriseDetailAPI(route.params.id as string)
  const {name,legalPerson,registeredAddress,industryCode,contact,contactNumber,businessLicenseId,businessLicenseUrl,businessLicenseName}=res.data
  addForm.value={
  name, // 企业名称
  legalPerson, // 法人
  registeredAddress, // 注册地址
  industryCode, // 所在行业
  contact, // 企业联系人
  contactNumber, // 联系人电话
  businessLicenseUrl, // 营业执照url
  businessLicenseId // 营业执照id
}
//编辑渲染初始图片
fileList.value=[{url:businessLicenseUrl,name:businessLicenseName}]
}
})
//修改企业
const updateEnterprise=async()=>{
  await addFormRef.value?.validate()
  try{
    await updateEnterpriseAPI({...addForm.value,id:Number(route.params.id)})
    router.back()
    ElMessage.success('修改成功！')
  }catch(err:any){
    ElMessage.error(err.response.data.msg)
  }
}
//重置表单
const resetForm=()=>{
  addFormRef.value?.resetFields()
  fileList.value=[]
}
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header :content="route.params.id?'修改企业':'添加企业'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form label-width="100px" :model="addForm" :rules="addFormRules" ref="addFormRef">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable>
                <el-option v-for="item in industryList" :value="item.industryCode"
                  :label="item.industryName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" maxlength="11" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload v-model:file-list="fileList" class="upload-demo" action="" :http-request="upload" :limit="1"
                list-type="picture" :on-remove="removeFile">
                <el-button type="primary" :disabled="fileList.length > 0">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    上传格式为jpg/png且文件大小不能超过500kb
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submit" v-if="!route.params.id">确定</el-button>
        <el-button type="primary" @click="updateEnterprise" v-else>修改</el-button>
        {{ addForm }}
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>